# -*- coding:utf-8 -*-

import random
import numpy as np


class Load(object):
    def __init__(self, path='model/'):
        self.path = path
        self.input_list, self.target = self.train_data(path + "trainSet1.txt")
        _, self.target_num = self.data_preprocess(path + '/data/PE_target')

    def data_preprocess(self, path):
        fp = open(path, 'r', encoding='UTF=8')
        target_content = []
        target_num = 0
        for line in fp:
            target_content.append(line)
            target_num += 1
        return target_content, target_num

    def train_data(self, path):
        fp = open(path, "r", encoding='UTF-8')
        input_list = []
        target = []
        for line in fp.readlines():
            line = line.strip()
            if line != "":
                input_vector = line.split("\t")
                label = random.randint(0, 14)
                target.append(label)
                input_list.append(input_vector)
        return input_list, target

    def data_iterator(self, input_data, input_target, batch_size=5, target_size=15, shuffle=False):
        if shuffle:
            indices = np.random.permutation(len(input_data))
            data_x = input_data[indices]
            data_y = input_target[indices] if np.any(input_target) else None
        else:
            data_x = input_data
            data_y = input_target
        total_processed_examples = 0
        total_steps = int(np.ceil(len(data_x)) / float(batch_size))
        for step in range(total_steps):
            batch_start = step * batch_size
            x = data_x[batch_start:batch_start + batch_size]
            y = None
            if np.any(data_y):
                y_indices = data_y[batch_start:batch_start + batch_size]
                y = np.zeros((len(x), target_size))
                y[np.arange(len(y_indices)), y_indices] = 1

            yield x, y
            total_processed_examples += len(x)

    @property
    def get_target_num(self):
        return self.target_num

    @property
    def get_input(self):
        return self.input_list

    @property
    def get_target(self):
        return self.target
